<template>
  <el-dialog
    :model-value="visible"
    :title="isEdit ? '编辑虚拟号码' : '创建虚拟号码'"
    width="500px"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="虚拟号码" prop="virtualNumber">
        <el-input 
          v-model="form.virtualNumber" 
          placeholder="请输入虚拟号码" 
          :disabled="isEdit"
        />
      </el-form-item>
      
      <el-form-item label="等级" prop="level">
        <el-select v-model="form.level" placeholder="请选择等级" style="width: 100%">
          <el-option label="高级" value="高级" />
          <el-option label="普通" value="普通" />
          <el-option label="专属" value="专属" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="费率(分/分钟)" prop="rate">
        <el-input 
          v-model.number="form.rate" 
          placeholder="请输入费率" 
          type="number"
        />
      </el-form-item>
      
      <el-form-item label="绑定手机号" prop="ownerPhone">
        <el-select 
          v-model="form.ownerPhone" 
          placeholder="请选择绑定手机号" 
          style="width: 100%"
          filterable
          clearable
        >
          <el-option
            v-for="phone in phoneNumbers"
            :key="phone.phone"
            :label="getPhoneLabel(phone)"
            :value="phone.phone"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
          <el-option label="未启用" :value="0" />
          <el-option label="正常使用" :value="1" />
          <el-option label="已注销" :value="2" />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { createVirtualNumberInfo, updateVirtualNumberInfo, getVirtualNumberInfoById } from '@/apis/virtualNumber'
import { getPhoneNumberInfo } from '@/apis/phoneNumber'

export default {
  name: 'CreateVirtualNumber',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    editId: {
      type: [String, Number],
      default: null
    },
    editData: {
      type: Object,
      default: null
    }
  },
  emits: ['update:visible', 'success'],
  setup(props, { emit }) {
    const formRef = ref()
    const submitLoading = ref(false)
    const phoneNumbers = ref([])
    
    const form = reactive({
      virtualNumber: '',
      level: '',
      rate: '',
      ownerPhone: '',
      status: 1
    })
    
    const rules = {
      virtualNumber: [
        { required: true, message: '请输入虚拟号码', trigger: 'blur' }
      ],
      level: [
        { required: true, message: '请选择等级', trigger: 'change' }
      ],
      rate: [
        { required: true, message: '请输入费率', trigger: 'blur' }
      ],
      ownerPhone: [
        { required: false, message: '', trigger: 'blur' }
      ],
      status: [
        { required: true, message: '请选择状态', trigger: 'change' }
      ]
    }
    
    // 获取手机号标签显示文本
    const getPhoneLabel = (phone) => {
      const phoneText = phone.phone || '';
      const customerText = phone.customerName || phone.name || phone.customer || '';
      if (customerText) {
        return `${phoneText} (${customerText})`;
      }
      return phoneText;
    };
    
    // 获取手机号列表
    const fetchPhoneNumbers = async () => {
      try {
        const res = await getPhoneNumberInfo();
        if (res && res.code === 0) {
          phoneNumbers.value = Array.isArray(res.data) ? res.data : [];
        }
      } catch (error) {
        console.error('获取手机号列表失败:', error);
        ElMessage.error('获取手机号列表失败');
        phoneNumbers.value = [];
      }
    };
    
    // 重置表单
    const resetForm = () => {
      Object.keys(form).forEach(key => {
        if (key === 'status') {
          form[key] = 1; // 默认状态为正常使用
        } else if (key === 'rate') {
          form[key] = '';
        } else {
          form[key] = '';
        }
      });
    };
    
    // 监听编辑ID变化，获取详情数据
    watch(
      () => [props.editId, props.editData],
      async ([newId, newData]) => {
        if (props.isEdit) {
          // 优先使用传入的editData，如果没有则通过API获取
          if (newData) {
            form.virtualNumber = newData.virtualNumber || '';
            form.level = newData.level || '';
            form.rate = newData.rate || '';
            form.ownerPhone = newData.ownerPhone || '';
            // 根据数据库结构，status 可能是 0, 1, 2
            form.status = parseInt(newData.status) || 0;
          } else if (newId) {
            try {
              const res = await getVirtualNumberInfoById(newId);
              if (res && res.code === 0 && res.data) {
                const data = res.data;
                form.virtualNumber = data.virtualNumber || '';
                form.level = data.level || '';
                form.rate = data.rate || '';
                form.ownerPhone = data.ownerPhone || '';
                // 根据数据库结构，status 可能是 0, 1, 2
                form.status = parseInt(data.status) || 0;
              }
            } catch (error) {
              console.error('获取虚拟号码信息失败:', error);
              ElMessage.error('获取虚拟号码信息失败');
            }
          }
        } else {
          resetForm();
        }
      },
      { immediate: true }
    );
    
    // 关闭弹窗
    const handleClose = () => {
      resetForm();
      emit('update:visible', false);
    };
    
    // 提交表单
    const handleSubmit = async () => {
      try {
        await formRef.value.validate();
        submitLoading.value = true;
        
        // 确保发送的数据格式正确
        const requestData = {
          virtualNumber: form.virtualNumber,
          level: form.level,
          rate: parseInt(form.rate), // 费率转换为整数
          ownerPhone: form.ownerPhone || null,
          status: parseInt(form.status) // 状态转换为整数
        };
        
        console.log('发送虚拟号码请求数据:', requestData);
        
        let res;
        if (props.isEdit) {
          // 编辑模式 - 直接使用virtualNumber作为主键，不传递id
          res = await updateVirtualNumberInfo(requestData);
        } else {
          // 创建模式
          res = await createVirtualNumberInfo(requestData);
        }
        
        if (res && res.code === 0) {
          ElMessage.success(`${props.isEdit ? '更新' : '创建'}成功`);
          resetForm();
          emit('success');
          handleClose();
        } else {
          ElMessage.error(res?.msg || `${props.isEdit ? '更新' : '创建'}失败`);
        }
      } catch (error) {
        console.error(`${props.isEdit ? '更新' : '创建'}虚拟号码失败:`, error);
        ElMessage.error(`${props.isEdit ? '更新' : '创建'}虚拟号码失败`);
      } finally {
        submitLoading.value = false;
      }
    };
    
    // 初始化获取手机号列表
    onMounted(() => {
      fetchPhoneNumbers();
    });
    
    return {
      formRef,
      form,
      rules,
      submitLoading,
      phoneNumbers,
      getPhoneLabel,
      resetForm,
      handleClose,
      handleSubmit
    };
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>